/**
 *
 */
package com.ebocy.hammer.core.socket.client;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.ebocy.hammer.core.handler.HandlerManager;
import com.ebocy.hammer.core.handler.IMessageHandler;
import com.ebocy.hammer.core.socket.MessageFilter;
import com.ebocy.hammer.core.socket.codecFilter.AsRequestDecoder;
import com.ebocy.hammer.core.socket.codecFilter.AsResponseEncoder;
import com.ebocy.hammer.core.util.ServerAddress;

/**
* @author lichunmei
* @date May 16, 2012 10:08:56 AM
*/
public class ServerConnector {
	/**
	 * 连接指定的服务器，并指定收到消息后的处理类
	 * @param serverAddress
	 * @param messageHandler
	 */
	public IoSession connect(ServerAddress serverAddress, IMessageHandler messageHandler) {
		SocketConnector connector = new NioSocketConnector();
		SocketAddress address = new InetSocketAddress(serverAddress.getIp(), serverAddress.getPort());
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new AsResponseEncoder(), new AsRequestDecoder()));
		connector.getFilterChain().addLast("message", new MessageFilter());
		connector.setHandler(new ClientIoHandler());
		SocketSessionConfig sessionConfig = connector.getSessionConfig();
		sessionConfig.setTcpNoDelay(true);
		ConnectFuture future = connector.connect(address);
		future.awaitUninterruptibly();
		IoSession session = future.getSession();

		HandlerManager.registerHandler(messageHandler);

		return session;
	}
}
